using System.Data;
using MySqlConnector;
namespace Front._1125;

public partial class AddBookForm : Form
{
    public AddBookForm()
    {
        InitializeComponent();
    }


    private void AddBookForm_Load(object sender, EventArgs e)
    {
        Init();
    }

    private void Init()
    {
        //加载出版社信息
        GetAllPublishers();
        //加载分类信息
        //加载书架信息
    }

    private void GetAllPublishers()
    {
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        string sql = "SELECT publisher_id,publisher_name FROM publisher_info;";
        MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sql, connection);
        //填充数据集
        DataSet dataSet = new DataSet();
        mySqlDataAdapter.Fill(dataSet, "publisher_info");

        if (dataSet.Tables["publisher_info"].Rows.Count > 0)
        {
            DataTable publisherTable = dataSet.Tables["publisher_info"];
            // 插入一行全部
            DataRow row = publisherTable.NewRow();
            row[0] = 0;
            row[1] = "全部";
            publisherTable.Rows.InsertAt(row, 0);

            publisher.DataSource = publisherTable;
            publisher.ValueMember = publisherTable.Columns[0].ColumnName;
            publisher.DisplayMember = publisherTable.Columns[1].ColumnName;
        }
    }


    private void button1_Click(object sender, EventArgs e)
    {
        string bookName = this.book_name.Text;
        string isbn = this.isbn.Text;
        //
        int publisherId = this.publisher.SelectedIndex;
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();

        string sql = "insert  into `book_info`(`isbn`,`book_name`,`author`,`publisher_id`,`publish_date`,`book_category`,`book_price`,`book_pages`,`book_desc`,`book_status`,`shelf_id`,`purchase_date`,`book_version`,`create_time`) values \n(@isbn,@book_name,'刘增杰',@publisher_id,'2021-06-01','计算机科学',59.80,320,'讲解MySQL基础与实战开发',1,1,'2023-01-10','第2版','2025-10-10 10:11:29');";
        
        using var command = new MySqlCommand(sql, connection);
        //设置参数
        command.Parameters.AddWithValue("isbn",isbn);
        command.Parameters.AddWithValue("book_name",bookName);
        command.Parameters.AddWithValue("publisher_id",publisherId);
        int count = command.ExecuteNonQuery();
        if (count > 0)
        {
            //添加成功
            MessageBox.Show("添加成功");
            this.DialogResult = DialogResult.OK;
            //关闭窗体
            this.Close();
            
        }
        else
        {
            //添加失败
            MessageBox.Show("添加失败");
            this.DialogResult = DialogResult.Cancel;
           
        }
    }

  
}